package net.loodies;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;

import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;

import android.widget.FrameLayout;

public class LoodiesAd extends FrameLayout implements
		AsyncResourceLoaderCallback, AcceleratorListener {

	private static final int BOUNCER = 0;
	private static final int TRAVELLER = 1;
	private static final int FIXED = 2;
	private static final int SPLASHSCREEN = 3;
	public boolean mHasEnded = false;

	String TAG = "LoodiesAd";

	Context mContext = null;
	
	AsyncResourceLoader mLoader = null;
	LoodiesErrorListener mErrorCB = null;

	Resource mResource = null;

	boolean mbAllowedToRun = false;

	float xx = 0;

	int posx = 0;
	int posy = 0;
	
	Quad2D mQuad = null;
	Quad2D mQuadAnchor = null;

	Quad2D mQuadContainer = null;
	Quad2D mQuadAd = null;
	Quad2D mQuadClose = null;

	Bitmap mAnchorBitmap = null;
	FSM mFSM = null;
	long mStartTime = 0;
	//private boolean mFirstTime = false;
	private long mPreviousTime = 0;

	private int mState = -1;

	private int mType;
	private boolean KillAndFinish = false;
	private long duration = 500;
	float orientationx = 0.0f;
	float orientationy = 0.0f;
	float orientationz = 0.0f;
	float accelerationx = 0.0f;
	float accelerationy = 0.0f;
	float accelerationz = 0.0f;
	float velocityx = 0.0f;
	float velocityy = 0.0f;
	private float3 mPosition = new float3(0, 0, 0);
	private int mWidthPixels;
	//private int mHeightPixels;
	int ROTATION = 0;
	Paint mPaint = null;
	int mAlpha = 0;
	private Activity mParentActivity = null;
	Rect mLocalRect = new Rect();
	Rect mGlobalRect = new Rect();
	public Callback mCallback;

	// --------------------------------------------
	// SetErrorCallback 
	// --------------------------------------------
	public void SetErrorCallback(LoodiesErrorListener loodiesErrorCallback) {
		mErrorCB = loodiesErrorCallback;
	}
	// --------------------------------------------
	// ctor 
	// --------------------------------------------
	public LoodiesAd(Context context) {
		super(context);
		this.mContext = context;
		mErrorCB = null;
		mbAllowedToRun = false;
		AccelerometerManager.setContext(context);

		if (AccelerometerManager.isSupported()) {
			AccelerometerManager.startListening(this);
		}
	}
	// --------------------------------------------
	// ctor with attributes
	// --------------------------------------------
	public LoodiesAd(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.mContext = context;
		AccelerometerManager.setContext(context);
	}
	// --------------------------------------------
	// Init()
	// --------------------------------------------
	void Init() {

		mStartTime = System.currentTimeMillis();
		
		if (mResource.mType.contains("fixed")) {
			mType = FIXED;
		}
		if (mResource.mType.contains("bouncer")) {
			mType = BOUNCER;
		}
		if (mResource.mType.contains("traveller")) {
			mType = TRAVELLER;
		}
		if (mResource.mType.contains("splashscreen")) {
			mType = SPLASHSCREEN;
		}
		
		
		Utils.ASSERT_AND_ERROR(mResource != null, " needs valid Resource",
				mErrorCB);
		if (mType == FIXED) {

			Utils.ASSERT_AND_ERROR(mResource.mFixedBitmap != null,
					" needs valid Resource.mFixedBitmap", mErrorCB);

			Bitmap bitmapAd = mResource.mMapBitmapNames.get("ad");
			Bitmap bitmapAnchor = mResource.mMapBitmapNames.get("anchor");
			if (bitmapAd == null) {
				return;
			}
			int w = bitmapAd.getWidth();
			int h = bitmapAd.getHeight();

			Utils.ASSERT_AND_ERROR(w == 0,
					" needs valid Resource.mFixedBitmap with width != 0",
					mErrorCB);
			Utils.ASSERT_AND_ERROR(h == 0,
					" needs valid Resource.mFixedBitmap with hright != 0",
					mErrorCB);

			mQuad = new Quad2D(w, h, 0, 0);
			mQuadAnchor = new Quad2D(w, 24, 0, 0);

			if (bitmapAnchor == null) {
				int[] colors = new int[w * 24];
				for (int i = 0; i < w * 24; i++) {
					colors[i] = 0xff000000;
				}
				Bitmap TabBmpRealFormat = Bitmap.createBitmap(colors, w, 24,
						Bitmap.Config.ARGB_8888);
				mAnchorBitmap = Bitmap.createScaledBitmap(TabBmpRealFormat,
						mWidthPixels, 24, false);
			} else {
				mAnchorBitmap = bitmapAnchor;
			}

			mFSM = new FSM();

			Rect globlalRect = new Rect();
			this.getGlobalVisibleRect(globlalRect);

			int2 startpos = new int2(0, globlalRect.height());
			int2 endpos = new int2(0, globlalRect.height() - h);

			mFSM.arrayStates.add(mFSM.new StateBANNER_IDLE_IN_START(mFSM, 500,
					startpos, startpos, "StateBANNERUP"));
			mFSM.arrayStates.add(mFSM.new StateBANNERUP(mFSM, 500, endpos,
					startpos, "StateBANNER_IDLE_IN_UP"));
			mFSM.arrayStates.add(mFSM.new StateBANNER_IDLE_IN_UP(mFSM, 5000,
					endpos, endpos, "StateBANNEDOWN"));
			mFSM.arrayStates.add(mFSM.new StateBANNER_IDLE_IN_DOWN(mFSM, 5000,
					startpos, startpos, "StateBANNER_IDLE_IN_DOWN"));
			mFSM.arrayStates.add(mFSM.new StateBANNERDOWN(mFSM, 500, startpos,
					endpos, "StateBANNER_IDLE_IN_DOWN"));
			mFSM.Start();
			
			
			
		}

		if (mType == BOUNCER || mType == TRAVELLER || mType == SPLASHSCREEN) {
			if(mResource.mBitmaps==null){
				mbAllowedToRun = false;
				Utils.ASSERT_AND_ERROR(mResource.mBitmaps==null,
						" needs valid mBitmaps ",
						mErrorCB);
				return;
			}
			if(mResource.mBitmaps.size()==0){
				mbAllowedToRun = false;
				Utils.ASSERT_AND_ERROR((mResource.mBitmaps.size()==0),
						" needs valid mBitmaps ",
						mErrorCB);
				return;
			}
			{
				int w = mResource.mBitmaps.get(0).getWidth();
				int h = mResource.mBitmaps.get(0).getHeight();
				mQuadAd = new Quad2D(w, h, 0, 0);
				mPaint = new Paint();
				mAlpha = 0;
			}
			// Do we need more than 1 bitmap
			if (mResource.mBitmaps.size() >1) {
				int w = mResource.mBitmaps.get(1).getWidth();
				int h = mResource.mBitmaps.get(1).getHeight();
				mQuadContainer = new Quad2D(w, h, 0, 0);
			}

			if (mResource.mBitmaps.size() >2) {
				int w = mResource.mBitmaps.get(2).getWidth();
				int h = mResource.mBitmaps.get(2).getHeight();
				mQuadClose = new Quad2D(w, h, 0, 0);
			}

		}
		mbAllowedToRun = true;

	}
	// --------------------------------------------
	// LoadAndStart called by launcher/wrapper
	// --------------------------------------------
	public void LoadAndStart(String slotID, String userID, Activity activity) {

		
		Utils.ASSERT_AND_ERROR(activity != null, " needs valid activity",
				mErrorCB);

		// Tell Manager who is the new LoodiesAd
		Manager.mFrameLayoutParent = this;
		duration = Manager.mTimeToDisapear;
		// Keep an Eye on source Activity

		setParentActivity(activity);

		DisplayMetrics displayMetrics = new DisplayMetrics();
		getParentActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(displayMetrics);
		mWidthPixels = displayMetrics.widthPixels;
	//	mHeightPixels = displayMetrics.heightPixels;

		// Don't run before loading done
		mbAllowedToRun = false;

		// build URL Swelen adress
		String strURL = "http://thx.swelen.com/mobileServe/"
				+ "?response=mixed&slot_uid=" + slotID + "&client_uid="
				+ userID;

		// Start loading, callback will get onFinishLoading
		mLoader = new AsyncResourceLoader(this, strURL, null, displayMetrics);
		ROTATION = getParentActivity().getWindowManager().getDefaultDisplay()
				.getOrientation();
	}
	// --------------------------------------------
	// onFinishLoading : called by loader callback
	// --------------------------------------------
	@Override
	public void onFinishLoading(Resource resource) {
	
		if(resource!=null){
			if(resource.IsValid()==false){
				mbAllowedToRun = false;
				mResource = null;
				Shutdown();
			}
			else {
				
				mResource = resource;
				Init();
			}
		}

		

	}
	// --------------------------------------------
	// Shutdown : 
	// --------------------------------------------
	public void Shutdown() {
		if (mLoader != null) {
			Log.v(TAG, "Shutdown()");
			mLoader.Shutdown();
		}
		KillAndFinish = true;
		this.mQuad = null;
		this.mResource = null;
		this.mQuadContainer = null;
		this.mQuadAnchor = null;
		this.mQuadClose = null;
		this.mFSM = null;
		this.mPaint = null;
		this.setParentActivity(null);
		mGlobalRect = null;
		mLocalRect = null;
	}

	// --------------------------------------------
	// dispatchDraw : called every frame, move things
	// --------------------------------------------
	@Override
	protected void dispatchDraw(Canvas canvas) {
		super.dispatchDraw(canvas);

		// draw each frame
		this.invalidate();
		if (KillAndFinish) {
			Log.v(TAG, "KillAndFinish = true");
			this.setVisibility(0);
			this.setFocusable(false);
			
			return;
		}
		if (!mbAllowedToRun) {
			mPreviousTime = System.currentTimeMillis();
			return;
		}
		

		long currentTime = System.currentTimeMillis();
		// if time elapsed
		if (currentTime > mStartTime + duration) {
			mState = 1;
			// set big value to not return here (in this if) soon
			// meanwhile mStae should be far far away,and loodies must have been
			// killed
			duration = 100000000;
			Log.v(TAG, "time is up !! mHasEnded = true call onEvent");
			mHasEnded = true;
			if(mCallback != null){
				//mCallback.OnEvent();
			//	return;
			}
		}

		
		float deltaLocal = currentTime - mPreviousTime;
		mPreviousTime = currentTime;
		if (mFSM != null) {
			mFSM.Update(deltaLocal);
		}

		if (mType == FIXED) {
			Bitmap bitmapAd = mResource.mMapBitmapNames.get("ad");
			if (bitmapAd == null) {
				return;
			}

			this.getGlobalVisibleRect(mGlobalRect);
			posy = mFSM.getPosition2D().y;

			// posy is in local space
			mQuad.UpdatePosition(posx + mGlobalRect.left, posy + mGlobalRect.top);
			mQuadAnchor.UpdatePosition(posx + mGlobalRect.left, posy
					+ mGlobalRect.top - 24);
			canvas.drawBitmap(bitmapAd, 0, posy, null);

			canvas.drawBitmap(mAnchorBitmap, 0, posy - 24, null);
			Paint paint = new Paint();
			paint.setStyle(Paint.Style.FILL);
			paint.setStrokeWidth(2);
			paint.setColor(Color.rgb(255, 128, 0));
			paint.setTextSize(18);

			canvas.drawText("PUB" + mResource.mMessageAnchor, 0, posy - 6,
					paint);
		}

		if (mType == SPLASHSCREEN) {

			if (mResource == null) {
				return;
			}
			Bitmap bmp0 = mResource.mBitmaps.get(0);
			if (bmp0 == null) {
				return;
			}

			this.getGlobalVisibleRect(mGlobalRect);

			xx += (deltaLocal * Manager.mBouncerSpeed);
			posy = 0;
			posx = mGlobalRect.width() / 2;

			if (mState > 0) {
				mState += mState;
				posx += mState;
			}
			if (mState > 1000) {
				KillAndFinish = true;
				if(mCallback != null){
					mCallback.OnEvent();
					return;
				}
			}
			// 1000 ms de 0 a 255
			// (deltaLocal/1000)* 255)
			mAlpha += (deltaLocal / 1000.0f) * 255;

			mPaint.setAlpha((mAlpha < 255) ? mAlpha : 255);
			mQuadAd.UpdatePosition(posx - bmp0.getWidth() / 2
					+ mGlobalRect.left, posy + mGlobalRect.top);
			// canvas.drawBitmap(bmp0, posx - bmp0.getWidth()/2 ,posy, null);
			mLocalRect.left = 0;
			mLocalRect.right = bmp0.getWidth();
			mLocalRect.top = 0;
			mLocalRect.bottom = bmp0.getHeight();
			mGlobalRect.left = posx - mGlobalRect.width() / 2;
			canvas.drawBitmap(bmp0, mLocalRect, mGlobalRect, mPaint);

		}

		if (mType == BOUNCER) {
			Bitmap bmp0 = mResource.mBitmaps.get(0);
			Bitmap bmp1 = mResource.mBitmaps.get(1);
			Bitmap bmp2 = mResource.mBitmaps.get(2);
			if (bmp0 == null) {
				return;
			}
			this.getGlobalVisibleRect(mGlobalRect);
			int maxdistance = mGlobalRect.height() / 2 - bmp0.getHeight();
			// deltaLocal ms
			// si on veut un tour en 4000 ms
			// alors steppixel = 4000/deltaLocal
			// 100 pix / s

			// 0.033 pix / ms

			xx += (deltaLocal * Manager.mBouncerSpeed);
			int uu = (int) (Math.cos((double) xx * 0.02) * maxdistance)
					+ mGlobalRect.height() / 2 - bmp0.getHeight() / 2;
			posy = uu;
			posx = mGlobalRect.width() / 2;
			if (mState > 0) {
				mState += mState;
				posx += mState;
			}
			if (mState > 1000) {
				KillAndFinish = true;
			}
			int offsetContainerY = (bmp1.getHeight() - bmp0.getHeight()) / 2;
			mQuadContainer.UpdatePosition(posx - bmp1.getWidth() / 2
					+ mGlobalRect.left, posy + mGlobalRect.top);
			canvas.drawBitmap(bmp1, posx - bmp1.getWidth() / 2, posy
					- offsetContainerY, null);

			mQuadAd.UpdatePosition(posx - bmp0.getWidth() / 2
					+ mGlobalRect.left, posy + mGlobalRect.top);
			canvas.drawBitmap(bmp0, posx - bmp0.getWidth() / 2, posy, null);

			int offsetCloseX = bmp0.getWidth() / 2 + bmp2.getWidth() / 2;
			int offsetCloseY = bmp0.getHeight() / 3;

			mQuadClose.UpdatePosition(posx - bmp2.getWidth() / 2
					+ mGlobalRect.left + offsetCloseX, posy + mGlobalRect.top
					- offsetCloseY);
			canvas.drawBitmap(bmp2, posx - bmp2.getWidth() / 2 + offsetCloseX,
					posy - offsetCloseY, null);

		}
		if (mType == TRAVELLER) {
			Bitmap bmp0 = mResource.mBitmaps.get(0);
			Bitmap bmp1 = mResource.mBitmaps.get(1);
			Bitmap bmp2 = mResource.mBitmaps.get(2);
			if (bmp0 == null) {
				return;
			}

			this.getGlobalVisibleRect(mGlobalRect);
			@SuppressWarnings("unused")
			int maxdistance = mGlobalRect.height() / 2 - bmp0.getHeight();
			// xx+= 300.0f / deltaLocal;
			// 0.016 pix / ms
			// xx+= (deltaLocal *Manager.mTravellerSpeed );
			// int uu = (int) (Math.cos((double)xx *
			// 0.02)*maxdistance)+globalRect.height()/2- bmp0.getHeight()/2;
			// posy = uu;
			// posx = globalRect.width()/2;

			mLocalRect.left  = mGlobalRect.left;
			mLocalRect.right = mGlobalRect.right-bmp0.getWidth();
			
			mLocalRect.top   = mGlobalRect.top-bmp0.getHeight()/2;
			mLocalRect.bottom= mGlobalRect.bottom-(bmp0.getHeight() / 2)-bmp0.getHeight()/2;
		
			if (mState > 0) {
				mState += mState;
				posx += mState;
			}
			else
			{
				int2 ipos = Transform.moveAccel(deltaLocal,mLocalRect,posx,posy,(ROTATION==1),Manager.mTravellerGravity);
				posx=ipos.x;
				posy=ipos.y;
			}
			if (mState > 1000) {
				KillAndFinish = true;
			}
			UpdateQuad(posx - (bmp1.getWidth()-bmp0.getWidth())/2,posy-(bmp1.getHeight()-bmp0.getHeight())/2,mLocalRect,bmp1,mQuadContainer,canvas);
						
			UpdateQuad(posx,posy,mLocalRect,bmp0,mQuadAd,canvas);
			int offsetCloseX = bmp0.getWidth() / 2 + bmp2.getWidth() / 2;
			int offsetCloseY = bmp0.getHeight() / 3;
			
			
			
		
			
			mLocalRect.left  = posx+offsetCloseX+bmp0.getWidth()/2;
			mLocalRect.right = posx+offsetCloseX+bmp2.getWidth()+bmp0.getWidth()/2;
			
			mLocalRect.top   = posy+offsetCloseY-bmp0.getHeight()/2;
			mLocalRect.bottom= posy+offsetCloseY+bmp2.getHeight()-bmp0.getHeight()/2;
			
			
			mQuadClose.UpdatePositionRect(mLocalRect);
			canvas.drawBitmap(bmp2, mLocalRect.left, mLocalRect.top, null);
			
			

		}

	}
	// --------------------------------------------
	// onTouchEvent(MotionEvent e)
	// --------------------------------------------
	public void UpdateQuad(int x,int y,Rect r,Bitmap bmp,Quad2D quad,Canvas canvas)
	{
		
		mLocalRect.left  = x;
		mLocalRect.right = x+bmp.getWidth();
		
		mLocalRect.top   = y;
		mLocalRect.bottom= y+bmp.getHeight();
		
		quad.UpdatePositionRect(mLocalRect);
		canvas.drawBitmap(bmp, mLocalRect.left, mLocalRect.top, null);

		
	}
	// --------------------------------------------
	// onTouchEvent(MotionEvent e)
	// --------------------------------------------
	@Override
	public boolean onTouchEvent(MotionEvent e) {
		Log.v(TAG, "onTouchEvent()");
		return super.onTouchEvent(e);
	}

	// --------------------------------------------
	// dispatchTouchEvent(MotionEvent e)
	// --------------------------------------------
	@Override
	public boolean dispatchTouchEvent(MotionEvent e) {

		if (KillAndFinish) {
			return super.dispatchTouchEvent(e);
		}

		boolean bTouched = false;
	
		
		int x = (int) e.getRawX()-mGlobalRect.left;
		int y = (int) e.getRawY()-mGlobalRect.top;
		
		String str = "onTouchEvent" + (int) e.getRawX() + " "+ (int) e.getRawY()+":"+x+" :"+y;
		
		
		if (mQuadAd != null) {
			if (mType == BOUNCER || mType == TRAVELLER || mType == SPLASHSCREEN) {
				if (mQuadAd.IsIn(x, y)) {
					str += " Inside Ad--- 8^[";
					Utils.GotoAdvitiser(getParentActivity(),
							mResource.mUrlNotification,
							mResource.mUrlDestination);
					bTouched = true;
				}
				if (mQuadClose != null && mQuadClose.IsIn(x, y)) {
					str += " Inside Close --- 8 Amchor^[";
					mState = 1;

					bTouched = true;

				}
			}
		}
		if (mQuad != null) {

			if (mType == FIXED) {
				if (mQuad.IsIn(x, y)) {
					str += " Inside --- 8^[";
					String currentState = mFSM.getCurrentStateName();
					if (currentState.contains("StateBANNER_IDLE_IN_UP")) {
						Utils.GotoAdvitiser(getParentActivity(),
								mResource.mUrlNotification,
								mResource.mUrlDestination);
					}
					bTouched = true;
				}
				if (mQuadAnchor.IsIn(x, y)) {
					str += " Inside --- 8 Amchor^[";
					String currentState = mFSM.getCurrentStateName();
					if (currentState.contains("StateBANNER_IDLE_IN_UP")) {
						mFSM.ChangeState("StateBANNERDOWN");

					} else if (currentState
							.contains("StateBANNER_IDLE_IN_DOWN")) {
						mFSM.ChangeState("StateBANNERUP");

					}
					bTouched = true;

				}
			}
		}
		Log.v(TAG, str);
		Manager.quadfocused = bTouched;
		if (bTouched == false) {
			super.dispatchTouchEvent(e);
		}
		return true;
	}
	// --------------------------------------------
	// onAccelerationChanged from AccelerometerManager
	// --------------------------------------------
	public void onAccelerationChanged(float x, float y, float z) {
		Manager.onAccelerationChanged(x, y, z);
		AccelerometerManager.acceleration.x=x;
		AccelerometerManager.acceleration.y=y;
		AccelerometerManager.acceleration.z=z;
	}
	// --------------------------------------------
	// onResume from AccelerometerManager
	// --------------------------------------------
	public void onResume() {
		if (AccelerometerManager.isSupported()) {
			AccelerometerManager.startListening(this);
		}

	}
	// --------------------------------------------
	// onPause
	// --------------------------------------------
	public void onPause() {

		if (AccelerometerManager.isListening()) {
			AccelerometerManager.stopListening();
		}

	}
	// --------------------------------------------
	// onStop
	// --------------------------------------------
	public void onStop() {

		if (AccelerometerManager.isListening()) {
			AccelerometerManager.stopListening();
		}

	}

	// --------------------------------------------
	// onDestroy
	// --------------------------------------------
	public void onDestroy() {

		if (AccelerometerManager.isListening()) {
			AccelerometerManager.stopListening();
		}

	}
	// --------------------------------------------
	// moveAccel
	// --------------------------------------------
	void moveAccel(float minx, float miny, float maxx, float maxy) {

		float gravity_factor = Manager.mTravellerGravity;
		float accel_duration = 0.0018f;
		float mps_to_pixel = 1;
		float friction = 0.8f; // 1-0.4/gravity; // 0.8

		// float bound_Y_min = -1.7f;
		// float bound_X_min = -0.66f;
		// float bound_Y_max = -0.80f;
		// float bound_X_max = 0.36f;

		float bound_Y_min = miny;
		float bound_X_min = minx;
		float bound_Y_max = maxy;
		float bound_X_max = maxx;
		if (ROTATION == 0) {
			accelerationx = Manager.accelerationx;
			accelerationy = Manager.accelerationy;
			accelerationz = Manager.accelerationz;

		}
		if (ROTATION == 1) {
			accelerationx = Manager.accelerationy * -1;
			accelerationy = Manager.accelerationx;
			accelerationz = Manager.accelerationz;

		}

		velocityx -= accelerationx * accel_duration * gravity_factor;
		velocityy -= accelerationy * accel_duration * gravity_factor;

		mPosition.x += velocityx * mps_to_pixel;
		mPosition.y += velocityy * mps_to_pixel;
		// if bounce we invert and reduce the direction

		if (mPosition.y < bound_Y_min) {
			velocityy = -velocityy * friction;
			velocityx = velocityx * friction;
			mPosition.y = bound_Y_min;

		}

		if (mPosition.y > bound_Y_max) {
			velocityy = -velocityy * friction;
			velocityx = velocityx * friction;
			mPosition.y = bound_Y_max;

		}

		if (mPosition.x < bound_X_min) {
			velocityx = -velocityx * friction;
			velocityy = velocityy * friction;
			mPosition.x = bound_X_min;

		}

		if (mPosition.x > bound_X_max) {
			velocityx = -velocityx * friction;
			velocityy = velocityy * friction;
			mPosition.x = bound_X_max;

		}

	}
	// --------------------------------------------
	// moveAccel
	// --------------------------------------------
	void moveAccel(Rect rect) {

		float gravity_factor = Manager.mTravellerGravity;
		float accel_duration = 0.0018f;
		float mps_to_pixel = 1;
		float friction = 0.8f; // 1-0.4/gravity; // 0.8

		// float bound_Y_min = -1.7f;
		// float bound_X_min = -0.66f;
		// float bound_Y_max = -0.80f;
		// float bound_X_max = 0.36f;

		float bound_Y_min = rect.top;
		float bound_X_min = rect.left;
		float bound_Y_max = rect.bottom;
		float bound_X_max = rect.right;
		if (ROTATION == 0) {
			accelerationx = Manager.accelerationx;
			accelerationy = Manager.accelerationy;
			accelerationz = Manager.accelerationz;

		}
		if (ROTATION == 1) {
			accelerationx = Manager.accelerationy * -1;
			accelerationy = Manager.accelerationx;
			accelerationz = Manager.accelerationz;

		}

		velocityx -= accelerationx * accel_duration * gravity_factor;
		velocityy -= accelerationy * accel_duration * gravity_factor;

		mPosition.x += velocityx * mps_to_pixel;
		mPosition.y += velocityy * mps_to_pixel;
		// if bounce we invert and reduce the direction

		if (mPosition.y < bound_Y_min) {
			velocityy = -velocityy * friction;
			velocityx = velocityx * friction;
			mPosition.y = bound_Y_min;

		}

		if (mPosition.y > bound_Y_max) {
			velocityy = -velocityy * friction;
			velocityx = velocityx * friction;
			mPosition.y = bound_Y_max;

		}

		if (mPosition.x < bound_X_min) {
			velocityx = -velocityx * friction;
			velocityy = velocityy * friction;
			mPosition.x = bound_X_min;

		}

		if (mPosition.x > bound_X_max) {
			velocityx = -velocityx * friction;
			velocityy = velocityy * friction;
			mPosition.x = bound_X_max;

		}

	}
	// --------------------------------------------
	//  @param mParentActivity
	//            the mParentActivity to set
	// --------------------------------------------
	public void setParentActivity(Activity mParentActivity) {
		this.mParentActivity = mParentActivity;
	}


	// --------------------------------------------
	//  @return the mParentActivity
	// --------------------------------------------
	public Activity getParentActivity() {
		return mParentActivity;
	}
	public boolean hasEnded() {
		// TODO Auto-generated method stub
		return mHasEnded;
	}

}
